<script setup lang="ts">
import { useSidebarColSpan } from '@/hooks';
import { getGoods } from '@/mock';
import { Goods } from '@/types';
import { getHandler, HandlerName } from '@/vm';
import { filter, find, isEmpty, uniq, uniqueId } from 'lodash';

const { log } = console

const modelIdInitValue = '3FO4F0QMUAXC'

const state = reactive({
  modelId: modelIdInitValue,
  goodsList: [] as Goods[],
  goodsType: '-1',
  goodsStyle: '-1',
  goodsSeries: '-1',
  goodsBrand: '-1',
  search: '',
})

onMounted(() => {
  fetchData()
})
watch(() => [
  // state.search,
  state.goodsType,
  state.goodsStyle,
  state.goodsSeries,
  state.goodsBrand,
], handleFilter)


const createModel = getHandler(HandlerName.StartDragProduct)
async function fetchData() {
  const goodsList = await getGoods()
  state.goodsList = goodsList.sort((a, b) => {
    return !a.tag && b.tag ? 1 : -1
  })
}
function handleBack() {
  log('back')
}
const searchVisible = ref(false)
function toggleSearch() {
  searchVisible.value = !searchVisible.value
}
function handleSearch() {
  handleFilter()
}


const goodsTypeOptions = computed(() => {
  const types = uniq(state.goodsList.map(goods => goods.type))
  return [addAllOption(), ...types.map((type) => {
    return {
      id: uniqueId(), name: type
    }
  })]
})
watchEffect(() => {
  log({ goodsTypeOptions })
})

type GoodsField = keyof Goods
function getOptionsFormGoodsList(goodsList: Goods[], field: GoodsField) {
  const options = uniq(goodsList.map(goods => goods[field]))
  return options.map((option) => {
    return {
      id: uniqueId(), name: option
    }
  })
}
const filterFields = (['style', 'series', 'brand']) as const
const [goodsStyleOptions, goodsSeriesOptions, goodsBrandOptions] = (filterFields).map(field => {
  return computed(() => {
    return [addAllOption(), ...getOptionsFormGoodsList(state.goodsList, field)]
  })
})
function addAllOption() {
  return {
    id: '-1',
    name: '全部'
  }
}

enum Sort {
  Up,
  Down
}
const sort = ref<Sort>(Sort.Up)
function toggleSort() {
  sort.value = sort.value === Sort.Up ? Sort.Down : Sort.Up
}

const filteredGoodsList = ref<Goods[]>(state.goodsList)
watchEffect(() => {
  filteredGoodsList.value = state.goodsList
})
function handleFilter() {
  filteredGoodsList.value = getFilteredGoodsList()
}

// function goodsFilter(options, id) { }
interface Option {
  id: string,
  name: string
}
function findOptionName(options: Option[], id: string) {
  if (id === '-1') return
  return find(options, { id })?.name
}
function addFilterObj(filterObj: Partial<Record<GoodsField, string>>, key: GoodsField, value?: string) {
  if (value) {
    filterObj[key] = value
  }
}
function getFilteredGoodsList() {
  const { search, goodsType, goodsStyle, goodsSeries, goodsBrand, goodsList } = state

  let list_f1 = filter(goodsList, (goods) => {
    return goods.name.indexOf(search) !== -1
  })

  const filterObj: Partial<Record<GoodsField, string>> = {}
  addFilterObj(filterObj, 'type', findOptionName(goodsTypeOptions.value, goodsType))
  addFilterObj(filterObj, 'style', findOptionName(goodsStyleOptions.value, goodsStyle))
  addFilterObj(filterObj, 'series', findOptionName(goodsSeriesOptions.value, goodsSeries))
  addFilterObj(filterObj, 'brand', findOptionName(goodsBrandOptions.value, goodsBrand))
  if (isEmpty(filterObj)) return list_f1
  const list_f2 = filter(list_f1, filterObj)
  return list_f2
}


const pageSize = 9
const allCount = computed<number>(() => {
  return filteredGoodsList.value.length
})
const pageState = reactive({
  pageNum: 1,
  pageSize: 9,
  total: allCount,
  pageCount: computed<number>(() => {
    return Math.ceil(allCount.value / pageSize)
    // return Math.ceil(pageState.allCount / pageState.pageSize)
  }),
  disablePre: computed<boolean>(() => {
    if (pageState.pageNum <= 1) {
      return true
    }
    return false
  }),
  disableNext: computed<boolean>(() => {
    if (pageState.pageNum >= pageState.pageCount) {
      return true
    }
    return false
  }),
})

function getPagedList(list: any[], { currentPage, currentPageSize }: { currentPage: number; currentPageSize: number }) {
  const pagedList = list.slice((currentPage - 1) * currentPageSize, currentPage * currentPageSize)
  return pagedList
}

const pagedGoodsList = computed(() => {
  const { pageNum: currentPage, pageSize: currentPageSize } = pageState
  return getPagedList(filteredGoodsList.value, { currentPage, currentPageSize })
})

</script>

<template>
  <div class="container">
    <el-row justify="space-between" align="middle">
      <el-button text @click="handleBack">
        <el-icon>
          <i-ep-arrow-left />
        </el-icon>
      </el-button>
      <span>全部</span>
      <el-button text @click="toggleSearch">
        <el-icon>
          <i-ep-search />
        </el-icon>
      </el-button>
      <el-input v-if="searchVisible" v-model="state.search">
        <template #append>
          <el-button text @click="handleSearch">
            <el-icon>
              <i-ep-search />
            </el-icon>
          </el-button>
        </template>
      </el-input>
    </el-row>

    <el-tabs v-model="state.goodsType">
      <el-tab-pane v-for=" goodsType in goodsTypeOptions" :label="goodsType.name" :name="goodsType.id"></el-tab-pane>
    </el-tabs>

    <el-row justify="space-around" align="middle" style="flex-wrap: nowrap;">
      <!-- <el-button text @click="toggleSort">
        <el-icon>
          <i-ep-sort-up v-if="sort === Sort.Up" />
          <i-ep-sort-down v-else />
        </el-icon>
      </el-button> -->
      <el-col :span="20">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-select v-model="state.goodsStyle" placeholder="风格">
              <el-option v-for="item in goodsStyleOptions" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="8">
            <el-select v-model="state.goodsSeries" placeholder="产品系列">
              <el-option v-for="item in goodsSeriesOptions" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="8">
            <el-select v-model="state.goodsBrand" placeholder="品牌">
              <el-option v-for="item in goodsBrandOptions" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-col>
        </el-row>
      </el-col>
      <!-- <el-button text @click="handleFilter">
        <el-icon>
          <i-ep-filter />
        </el-icon>
      </el-button> -->
    </el-row>


    <GoodsCardContainer>
      <GoodsCard v-for="goods in pagedGoodsList" :key="goods.id" v-bind="goods" @click="() => createModel(goods.id)"
        @dragstart="() => createModel(goods.id)" />
    </GoodsCardContainer>

    <div class="footer">
      <el-pagination v-model:currentPage="pageState.pageNum" layout="prev, slot, next" :total="pageState.total">
        <div class="pagination-indicator">{{ pageState.pageNum }}/{{ pageState.pageCount }}</div>
      </el-pagination>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.container {
  overflow: hidden;
  padding: 10px;
  height: 100vh;
  position: relative;
}

.pagination-indicator {
  width: 100%;
  text-align: center;
  font-size: var(--el-pagination-font-size);
}

.footer {
  position: fixed;
  bottom: 0;
  width: 100%;
  left: 0;
  right: 0;
  margin: auto;
  background: white;
}
</style>